﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Store.Manager.ERP.Common.Models;

namespace Api.Core.Filters
{
    /// <summary>
    /// model校验自定义，需配置
    /// </summary>
    public class Filter_ModelValidAction:ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                //公共返回数据类
                CommonResponse returnMsg = new CommonResponse();

                //获取具体的错误消息
                foreach (var item in context.ModelState.Values)
                {
                    //遍历所有项目的中的所有错误信息
                    foreach (var err in item.Errors)
                    {
                        //消息拼接,用|隔开，前端根据容易解析
                        returnMsg.Message += $"{err.ErrorMessage}|";
                    }
                }
                //去除最后一个分隔符
                returnMsg.Message = returnMsg.Message.Substring(0, returnMsg.Message.Length - 1);
                context.Result = new JsonResult(returnMsg);
            }
        }
    }
}
